/*
 * @Description: 全宗reducer
 * @Author: Rfan
 * @Date: 2022-05-30 14:43:58
 * @LastEditTime: 2022-06-15 14:34:13
 */

import { delItemByIdArray, editItemById, insertItemAfter } from '@/utils/list';
import {
  SET_METADATA_LIST,
  SET_SELECT_AT,
  SET_SELECT_FOND,
  SET_SELECT_LEVEL,
  ADD_RELY,
  DELETE_RELY,
  SET_RELY_LIST,
  SET_SELECTED_ITEM,
  EDIT_RELY
} from '../constants';

export const MetadataRelyReducer = (state, action) => {
  switch (action.type) {
    // 设置选中的全宗
    case SET_SELECT_FOND:
      return {
        ...state,
        selectFond: action.data
      };

    // 设置选中的档案类型
    case SET_SELECT_AT:
      return {
        ...state,
        selectAT: action.data
      };

    // 设置选中的层级
    case SET_SELECT_LEVEL:
      return {
        ...state,
        selectLevel: action.data
      };

    /**
     * @description: 保存表格选中的条目id
     * @param {number[]} data
     */
    case SET_SELECTED_ITEM:
      return { ...state, selectItems: action.data };

    /**
     * @description: 设置依赖列表
     * @param {Array} data 请求到的列表
     */
    case SET_RELY_LIST:
      return {
        ...state,
        inheritList: action.data
      };

    /**
     * @description: 加载层级元数据列表
     * @param {number} level 请求的层级
     * @param {IMetadata[]} data 该层级的元数据
     */
    case SET_METADATA_LIST: {
      const { level, data } = action;
      const levelMatedata = {
        ...state.levelMatedata,
        [level]: data
      };
      return {
        ...state,
        levelMatedata
      };
    }

    /**
     * @description: 添加元数据依赖条目
     */
    case ADD_RELY:
      return {
        ...state,
        inheritList: insertItemAfter(action.data, state.inheritList)
      };

    /**
     * @description: 添加元数据依赖条目
     */
    case EDIT_RELY:
      return {
        ...state,
        inheritList: editItemById(action.id, action.data, state.inheritList)
      };

    /**
     * @description: 删除元数据依赖条目
     */
    case DELETE_RELY:
      return {
        ...state,
        inheritList: delItemByIdArray(action.ids, state.inheritList)
      };

    default:
      console.log('untouched', action);
      return state;
  }
};
